package com.design.marketPrj.application.controller.user;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.design.marketPrj.application.bean.PO.Storage;
import com.design.marketPrj.application.bean.PO.StorageExample;
import com.design.marketPrj.application.bean.ResponseResult;
import com.design.marketPrj.application.bean.layuiJSON;
import com.design.marketPrj.application.controller.BaseController;
import com.design.marketPrj.application.mapper.StorageMapper;
import com.design.marketPrj.application.service.ExcludeDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.RegEx;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/userProduct")
public class UserProductController extends BaseController {
    @Autowired
    StorageMapper storageMapper;
    @Autowired
    ExcludeDataService excludeDataService;

    @RequestMapping("/index")
    public String userProduct(Model model){
        model.addAttribute("user",getUser());
        return "user/userProduct";
    }

    @RequestMapping("/sellConfirm")
    public String userProductSellConfirm(String maxAmount,String code,Model model){
        model.addAttribute("user",getUser());
        model.addAttribute("maxAmount",maxAmount);
        model.addAttribute("code",code);
        return "user/userSell";
    }

    @RequestMapping("/list")
    @ResponseBody
    public layuiJSON userList(){
        layuiJSON layuiJSON = new layuiJSON();

        StorageExample storageExample = new StorageExample();
        storageExample.or().andUserIdEqualTo(getUserId());
        List<Storage> list = storageMapper.selectByExample(storageExample);
        List<String> inputList = list.stream().map(Storage::getProductCode).collect(Collectors.toList());
        Map codeToWorth = excludeDataService.getCurrentWorth(inputList);
        JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(list));
        for(Object o : jsonArray){
            JSONObject jsonObject = (JSONObject)o;
            String code = (String)jsonObject.get("productCode");
            BigDecimal amount = (BigDecimal) jsonObject.get("amount");
            BigDecimal worth = (BigDecimal) codeToWorth.get(code);
            jsonObject.put("value",amount.multiply(worth).setScale(2,BigDecimal.ROUND_HALF_UP));
        }
        layuiJSON.setData(jsonArray);
        layuiJSON.setMsg("");
        layuiJSON.setCode(0);
        layuiJSON.setCount(list.size());
        return layuiJSON;
    }

}
